;*****************************************************
; 	Copyright (C) SEIKO EPSON CORP. 1997-2001
;	All rights Reserved
;
;	File name : memmove.s
;	Function  :
;	       This is memmove function
;	History   :
;		1997/03/24		V.Chan	start
;		1997/03/26		added comments and optimized
;		1997/03/31		removed delayed jump after memory write (ln 62)
;		2001/12/06		T.Tazaki for GNU33(Linux)
;*****************************************************

;*****************************************************
; memmove
;		memory copy from src to dest, N bytes
;		overlap of memory will not affect result
;
;		case1:	dest = [............]
;				src	 =		[..............]
;		copy from head of src to head of dest
;
;		case2:	src	 =		[..............]
;				dest = [............]
;		copy from tail of src to tail of dest
;
; arguments : %r6:dest addr, %r7:src addr, %r8 byte number
; return    : %r4:dest addr
; comment   : destroy %r9
;*****************************************************

	.section .text
	.align 1
	.global memmove
	.type	 memmove,@function

memmove:
	cmp		%r6, %r7		; cmp starting addresses
	jrgt.d	continue
	ld.w 	%r4, %r6		; return dest addr
	jp		memmove_loop

continue:
; prepare for reverse copying
	sub		%r8, 1
	ld.w	%r10, %r6
	add		%r10, %r8		; dest addr + diff
	ld.w	%r11, %r7
	add		%r11, %r8		; src addr + diff

reverse_loop:
	cmp		%r11, %r7
	jrlt	memmove_ret
	ld.ub	%r9, [%r11]	; copy src 1 byte to dest
	ld.b	[%r10], %r9
	sub		%r11, 1		; decrement counter
	jp.d	reverse_loop
	sub		%r10, 1

memmove_loop:
	cmp		%r8, 0
	jreq	memmove_ret
	ld.ub	%r9, [%r7]+	; copy src 1 byte to dest
	ld.b	[%r6]+, %r9
	sub		%r8, 1		; decrement counter
	jp		memmove_loop

memmove_ret:
	ret
